<template>
  <div>
    <input type="file" @change="handleFileChange" />
    <button @click="uploadFile">Upload</button>
    <div v-if="progress > 0">Uploading: {{ progress }}%</div>
  </div>
</template>

<script>
import axios from 'axios';
import  {initiate} from "@/api/shareDrive/upload";
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      file: null,
      chunkSize: 1024 * 1024 * 5, // 5MB per chunk
      totalChunks: 0,
      uploadedChunks: 0,
      progress: 0,
      fileId: '' // This will be provided by the backend after initiating the upload
    };
  },
  methods: {
    handleFileChange(event) {
      this.file = event.target.files[0];
      this.totalChunks = Math.ceil(this.file.size / this.chunkSize);
    },
    async initiateUpload() {
      const formData = new FormData();
      formData.append('file', this.file, this.file.name);

      await initiate(formData).then(response => {
        console.log('--------2-------')
        console.log(response)

        this.fileId = response.fileId;
        console.log(response.fileId)
        alert(response.fileId)
      });

      // const response = await axios.post(process.env.VUE_APP_BASE_API + '/shareDive/upload/initiate', formData, {
      //   headers: {
      //     'Content-Type': 'multipart/form-data',
      //     'Authorization': 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      //
      //   }
      // });

    },
    async uploadChunk(chunk) {
      const formData = new FormData();
      formData.append('chunk', chunk);
      formData.append('fileId', this.fileId);
      formData.append('chunkNumber', this.uploadedChunks + 1);
      formData.append('totalChunks', this.totalChunks);

      await axios.post(process.env.VUE_APP_BASE_API + `/shareDive/upload/chunk`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
        }
      });

      this.uploadedChunks++;
      this.progress = Math.floor((this.uploadedChunks / this.totalChunks) * 100);
    },
    async uploadFile() {
      console.log('--------1-------')
      await this.initiateUpload();
      console.log('--------3-------')
      const totalChunks = this.totalChunks;
      for (let start = 0; start < this.file.size; start += this.chunkSize) {
        const end = Math.min(start + this.chunkSize, this.file.size);
        const chunk = this.file.slice(start, end);

        await this.uploadChunk(chunk);
      }

      // Optionally, notify the backend that all chunks have been uploaded
      await axios.post(process.env.VUE_APP_BASE_API + `/shareDive/upload/complete/${this.fileId}`,null,{
        headers: {
          'Authorization': 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
        }
      });

      this.progress = 0;
      this.uploadedChunks = 0;
      this.file = null;
      alert('Upload complete!');
    }
  }
};
</script>
